package com.freshcity.page.talk
{
	import com.freshcity.component.BaseGameObject;
	import com.freshcity.component.container.Component;
	import com.freshcity.component.container.VBox;
	import com.freshcity.component.text.RichTextField;
	import com.freshcity.component.text.plugins.ShortcutPlugin;
	import com.freshcity.core.Dispatcher;
	import com.freshcity.core.GlobalVar;
	import com.freshcity.core.OpCodes;
	import com.freshcity.graphics.CommentPanel;
	import com.freshcity.graphics.TalkWin;
	import com.freshcity.lib.event.DataEvent;
	import com.freshcity.lib.event.EventName;
	import com.freshcity.manager.LayerManager;
	import com.freshcity.page.feedback.FeedBack;
	import com.freshcity.page.friend.RequestFriend;
	import com.freshcity.page.wait.RoomList;
	import com.freshcity.page.zhitiao.RequestDate;
	import com.freshcity.utils.BitmapUtil;
	import com.freshcity.utils.GlobalUtil;
	import com.freshcity.utils.StringUtil;
	import com.greensock.TweenLite;
	import com.greensock.TweenMax;
	import com.greensock.easing.Strong;
	import com.pblabs.debug.Logger;
	
	import fl.controls.Button;
	import fl.controls.CheckBox;
	import fl.controls.UIScrollBar;
	
	import flash.display.DisplayObjectContainer;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	import flash.ui.Keyboard;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;
	

	public class Talk extends Component
	{
		public var win:TalkWin;
		
		private var _output:RichTextField;
		private var _outputScrollBar:UIScrollBar;
		private var _input:RichTextField;
		
		//smileys
		private var _smileys:Array = [jAcid_smiley, jCool_smiley, 
			jSad_smiley, jShocked_smiley,jUnhappy_smiley];
		
		private var niFormat:TextFormat = new TextFormat("宋体", 12, 0x339933, false);	
		private var woFormat:TextFormat = new TextFormat("宋体", 12, 0x000080, false);		
		private var taFormat:TextFormat = new TextFormat("宋体", 12, 0x663333, false);
		private var warnFormat:TextFormat = new TextFormat("宋体", 12, 0xff0000, false);
		
		private var _smileyContainer:Sprite;
		private var _sendBtn:Button;
		private var room:*;
		private var commentPanel:CommentPanel;
		private var viewBtn:TextField;
		
		public var toUser:*;
		public var toUserReport:*;
		private var guanzhu:RequestFriend;
		private var talkDone:Boolean;
		
		
		public function Talk(parent:DisplayObjectContainer=null, xpos:Number=0, ypos:Number=0)
		{
			this.visible = false;
			this._width = 560;
			this._height = 500;
			super(parent, xpos, ypos);
			
			commentPanel.closeBtn.addEventListener(MouseEvent.CLICK,onHideCommentPanel);
			win.addTaCheckBox.addEventListener(MouseEvent.CLICK,onGuanZhuHandler);
			win.closeBtn.addEventListener(MouseEvent.CLICK,onCloseTalk);
			win.giftBtn.addEventListener(MouseEvent.CLICK,onGiftBtnHandler);
			Dispatcher.addEventListener(EventName.ReqFriendDone,onReqFriendDoneHandler);
		}
		
		private function onReqFriendDoneHandler(evt:DataEvent):void
		{
			var data:* = evt.data;
			if(data.id==this.toUser.id){
				main.msg.showRollTipsMsg("操作成功");
				main.friendPanel.addFriend(data);
				win.addTaCheckBox.visible = false;
				win.giftBtn.visible = true;
			}
		}
		
		override public function hide(event:Event=null):void
		{
			TweenMax.to(this, 0.5, {autoAlpha: 0, y: "-50",onComplete:destroy});
		}
		
		override public function show(event:Event=null):void
		{
			if (!this.parent)
			{
				LayerManager.sceneLayer.addChild(this);
				this.x=(this.stage.stageWidth-this.width) / 2;
				this.y=(this.stage.stageHeight-this.height) / 2 + 30 -50;
			}
			
			TweenMax.to(this, 0.5, {autoAlpha: 1, y: "+50"});
		}
		
		override protected function addChildren():void
		{
			super.addChildren();
			
			win = new TalkWin();
			addChild(win);
			
			viewBtn = StringUtil.addHyLink("关于他的评论 >>","",onQueryCommentPanel);
			viewBtn.visible = false;
			viewBtn.x = 460;
			viewBtn.y = 40;
			win.addChild(viewBtn);
			
			var mask:Shape = new Shape();
			mask.graphics.beginFill(0xffffff);
			mask.graphics.drawRect(392,35,170,465);
			win.addChild(mask);
			
			commentPanel = new CommentPanel();
			commentPanel.name = "commentPanel";
			//commentPanel.x = 387;
			commentPanel.x = win.width;
			commentPanel.y = 35;
			commentPanel.mask = mask;
			//win.addChild(commentPanel);
			
			initChatPanel();
			//group.commu.register(OpCodes.REQUEST_DATE,onRequestDate);
		}
		
		private function onGetFlower(data:*):void
		{
			if(data is String){
				main.msg.showRollTipsMsg(data);
			}else{
				var msg:String="【系统】TA给你送了一枚玫瑰 ，你的美誉度提升了。";
				main.msg.showFixRollMsg("用户" + toUser.id + "给你送了一枚玫瑰");
				importOutPut(msg,niFormat);
			}
		}
		
		protected function onGiftBtnHandler(event:MouseEvent):void
		{
			main.commu.send(OpCodes.SEND_FLOWER,{},onSendFlower);
		}
		
		private function onSendFlower(data:*):void
		{
			var msg:String;
			if(data is String){
				msg = "【系统】".concat(data);
			}else{
				msg = "【系统】你给TA送了一枚玫瑰，你的荣誉度提升了。你对TA的友好度提升了。";
				main.friends[data.id].assoValue ++;
			}
			importOutPut(msg,niFormat);
		}
		
		protected function onCloseTalk(event:MouseEvent):void
		{
			if(this.talkDone){
				this.onLeaveTalk();
			}else{
				main.commu.send(OpCodes.END_TALK,{});
			}
		}
		
		protected function onGuanZhuHandler(e:MouseEvent):void
		{
			var cb:CheckBox = CheckBox(e.target);
			if(cb.selected == true){
				if (GlobalUtil.dictLen(main.friends) >= GlobalVar.MAX_FRIEND_AMT)
				{
					main.msg.showRollTipsMsg("意中人总数不能超过" + GlobalVar.MAX_FRIEND_AMT + "个");
				}else{
					guanzhu = new RequestFriend(this.toUser);
					guanzhu.main = this.main;
					guanzhu.show();
				}
			}else{
				if(guanzhu)guanzhu.hide();
			}
		}
		
		private function initChatPanel():void
		{
			//output border
			var outputBorder:Shape = new Shape();
			outputBorder.graphics.lineStyle(1, 0x666666);
			outputBorder.graphics.drawRect(10, 45, 380, 325);
			win.addChild(outputBorder);
			
			//output richtextfield
			_output = new RichTextField();
			_output.x = 15;
			_output.y = 50;
			_output.setSize(360, 325);
			_output.lineHeight = 22;
			_output.autoScroll = true;
			win.addChild(_output);
			
			//output scrollbar
			_outputScrollBar = getUIScrollBar();			
			_outputScrollBar.scrollTarget = _output.textfield;
			_outputScrollBar.x = 10 + outputBorder.width-_outputScrollBar.width;
			_outputScrollBar.y = 45;
			_outputScrollBar.height = _output.height;	
			win.addChild(_outputScrollBar);	
			
			_output.html = false;
			
			var inputBorder:Shape = new Shape();
			inputBorder.graphics.lineStyle(1, 0x666666);
			inputBorder.graphics.drawRect(10, 395, 380, 25);
			win.addChild(inputBorder);
			
			//input richtextfield			
			_input = new RichTextField();
			_input.setSize(380, 25);
			_input.type = RichTextField.INPUT;
			_input.x = 10;
			_input.y = 395;	
			_input.textfield.multiline = false;
			win.addChild(_input);
			
			_input.html = false;
			_input.caretIndex = _input.contentLength;
			
			//add smileys
			_smileyContainer = new Sprite();
			win.addChild(_smileyContainer);
			_smileyContainer.x = 25;
			_smileyContainer.y = _input.y + _input.viewHeight + 20;
			createSmileys();
			
			//send button
			_sendBtn = new Button();
			win.addChild(_sendBtn);
			_sendBtn.x = 290;
			_sendBtn.y = 435;
			_sendBtn.setSize(100,22);
			_sendBtn.label = "发送";
			_sendBtn.addEventListener(MouseEvent.CLICK, onSendMessage);
			
			//shortcut plugin
			var splugin:ShortcutPlugin = new ShortcutPlugin();		
			var shortcuts:Array = [ { shortcut:"/a", src:_smileys[0] },
				{ shortcut:"/b", src:_smileys[1] },
				{ shortcut:"/c", src:_smileys[2] },
				{ shortcut:"/d", src:_smileys[3] },
				{ shortcut:"/e", src:_smileys[4] },
				{ shortcut:"/f", src:_smileys[5] },
				{ shortcut:"/g", src:_smileys[6] },
				{ shortcut:"/h", src:_smileys[7] },
				{ shortcut:"/i", src:_smileys[8] } ];
			splugin.addShortcut(shortcuts);
			_input.addPlugin(splugin);			
			
			//chatArea.condenseWhite = true;
			//chatArea.addEventListener(TextEvent.TEXT_INPUT,announceEvent);
			//chatArea.addEventListener(ComponentEvent.ENTER,onEnterDown);			
			//sendBtn.addEventListener(MouseEvent.CLICK, onSendMessage);			
		}
		
		protected function onHideCommentPanel(event:MouseEvent):void
		{
			TweenMax.to(commentPanel,0.5,{x:win.width,autoAlpha:0});
		}		
		
		protected function onQueryCommentPanel(event:Event):void
		{
			main.commu.send(OpCodes.QUERY_COMMENT,{uid:toUser.id},onShowCommentPanel);
		}
		
		public function set data(data:*):void
		{
			main.msg.showFixRollMsg("您和用户"+data.user.id+"开始了交谈。");
			talkDone = false;
			
			this.room = data.room;
			this.toUser = data.user;
			this.toUserReport = data.report;
			this._sendBtn.enabled = true;
			this._output.clear();
			this._input.clear();
			
			if(data.isFriend){
				win.addTaCheckBox.visible = false;
				win.giftBtn.visible = true;
			}else{
				win.addTaCheckBox.visible = true;
				win.giftBtn.visible = false;
			}
			
			win.closeBtn.visible = false;
			TweenLite.delayedCall(GlobalVar.TALK_LOCK_LEN,unlockTime);
			
			if(main.user.level > 4){
				viewBtn.visible = true;
			}
			
			TweenLite.delayedCall(2,welcome);
			
			win.userPic.gotoAndStop(data.user.sex);
			BitmapUtil.showAvatarPic(data.user,win.userPic);
			
			setInfoPanel();
			//setCommentPanel(user);
			main.commu.register(OpCodes.END_TALK,onEndTalk);
			main.commu.register(OpCodes.TALK,onTalk);
			main.commu.register(OpCodes.GET_FLOWER,onGetFlower);
			main.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			main.stage.focus = _input.textfield;	
		}
		
		private function unlockTime():void
		{
			var pubMsg1:String = "【提示】绑定解除，您现在随时可以点击右上方按钮退出聊天。";
			importOutPut(pubMsg1,niFormat);
			win.closeBtn.visible = true;
		}
		
		private function onShowCommentPanel(data:*):void
		{
			var comBox:VBox = new VBox();
			var format:TextFormat = new TextFormat("宋体", 12, 0x000000, false, false, false);
			format.leading = 8;
			format.letterSpacing = 0;	
			var line:Shape;
			
			var label:TextField;
			
			for each (var c:Object in data) 
			{
				label = new TextField();
				label.defaultTextFormat = format;
				label.wordWrap = true;
				label.multiline = true;
				label.width = 120; 
				label.autoSize = TextFieldAutoSize.LEFT;
				label.htmlText = "".concat("<p>",c.content," (",c.time,")</p>");
				comBox.addChild(label);
				
				line = new Shape();
				line.graphics.beginFill(0x999999);
				line.graphics.drawRect(3,0,136,1);
				line.graphics.endFill();
				comBox.addChild(line);
			}
			comBox.initialize();
			commentPanel.panel.source = comBox;
			if(!win.contains(commentPanel)){
				win.addChild(commentPanel);
			}
			TweenMax.to(commentPanel,0.5,{x:392,autoAlpha:1});
		}
		
		private function setInfoPanel():void
		{
			var propertyBox:UserDetailPanel = new UserDetailPanel(this.toUser,this.toUserReport);
			propertyBox.main=main;
			propertyBox.name = "userInfo";
			win.infoPanel.source = propertyBox;
		}
		
		override public function destroy():void
		{
			win.addTaCheckBox.selected=false;
			_output.clear();
			if(win.contains(commentPanel)){
				win.removeChild(commentPanel);
			}			
			main.commu.unRegister(OpCodes.END_TALK);
			main.commu.unRegister(OpCodes.TALK);
			main.commu.unRegister(OpCodes.GET_FLOWER);
			super.destroy();
		}
		
		private function welcome():void
		{
			var pubMsg1:String = "【广播】欢迎光临，".concat("您有",room.inteval/60,"分钟交流时间！");
			//importOutPut(pubMsg1,niFormat);
			var pubMsg2:String = "【提示】虽是自由畅谈，但安全第一。交流中若涉及姓名，电话，邮箱，QQ号码以及金钱交易方面的，请分外留神！";
			importOutPut(pubMsg2,warnFormat);
			var pubMsg3:String = "【警告】谈话中请勿涉及任何反动，情色，暴力，人身侮辱，商业广告等言辞，一旦发现请联系客服举报。";
			//importOutPut(pubMsg3,warnFormat);
		}		
		
		private function onKeyDown(evt:KeyboardEvent):void
		{			
			if (evt.keyCode == Keyboard.ENTER && _input.contentLength > 0)
			{				
				onSendMessage();
			}
		}		
		
		private function endRemind():void
		{
			var pubMsg1:String = "【广播】".concat("交流结束","，欢迎下次光临...",currentTimeStr());
			importOutPut(pubMsg1,warnFormat);
			main.commu.send(OpCodes.END_TALK,{});
		}
		
		private function currentTimeStr():String
		{
			var dt:Date = new Date();
			return "".concat("(",dt.hours,":",dt.minutes,":",dt.seconds,")");
		}
		
		protected function onSendMessage(evt:MouseEvent = null):void
		{
			var message:String = _input.converRichToString();
			if(message.length>0){
				main.commu.send(OpCodes.TALK, {msg:message});
				
				var s:String = "我 "+currentTimeStr();
				importOutPut(s,woFormat);
				
				Logger.debug(this,"onSendMessage",message);
				importOutPut("  " + message);
			}			
			
			this.updateOutput();
			_input.clear();			
		}
		
		private function onTalk(data:Object):void
		{
			var s1:String = "TA "+currentTimeStr();
			importOutPut(s1,taFormat);
			
			var s2:String = String(data['msg']);
			Logger.debug(this,"onReceiveMessage",s2);
			importOutPut("  " + s2);
			//_output.verticalScrollBar.scrollPosition = _output.verticalScrollBar.maxScrollPosition;
		}
		
		private function onLeaveTalk():void
		{
			main.layer.comeIn();
			this.hide();
		}
		
		private function onEndTalk(data:*):void
		{
			this._sendBtn.enabled = false;
			if(data=='userLeave'){
				var pubMsg1:String = "【广播】".concat("对方已离开谈话，您现在可以点击右上方按钮退出聊天！");
				importOutPut(pubMsg1,niFormat);
				talkDone = true;
				win.closeBtn.visible = true;
			}else{
				onLeaveTalk();
			}
		}
		
		public function importOutPut(msg:String,format:TextFormat=null):void
		{
			_output.importString(msg,format);
			_outputScrollBar.update(); 
		}
		
		private function insertSmiley(evt:MouseEvent):void
		{
			var smiley:Sprite = evt.currentTarget as Sprite;
			var smileyClass:Class = getDefinitionByName(getQualifiedClassName(smiley)) as Class;
			_input.insertSprite(smileyClass, _input.textfield.caretIndex);					
			//_inputScrollBar.update();
			
			//correct caretIndex of input
			if (_input.isSpriteAt(_input.caretIndex))
			{				
				_input.caretIndex++;
			}
		}
		
		private function createSmileys():void
		{
			for (var i:int = 0; i < _smileys.length; i++)
			{
				var smiley:Sprite = new _smileys[i]() as Sprite;
				_smileyContainer.addChild(smiley);
				smiley.x = (i % 8) * 35;
				smiley.y = Math.floor(i / 8) * 30;
				smiley.buttonMode = true;
				smiley.addEventListener(MouseEvent.CLICK, insertSmiley);			
			}
		}
		
		private function getUIScrollBar():UIScrollBar
		{
			var scrollBar:UIScrollBar = new UIScrollBar();
			return scrollBar;
		}
		
		public function updateOutput():void
		{
			if (_output.textfield.maxScrollV > 1)_output.textfield.scrollV = _output.textfield.maxScrollV;
		}

	}
}
